package com.cskaoyan.connectionpool;

import com.cskaoyan.utils.JDBCUtils;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 创建日期: 2022/08/26 16:12
 *
 * @author ciggar
 *
 * 1. 干掉代码中的魔法值
 *
 * 2. 让一些常量可以让用户自己配置
 *
 */
public class MyConnectionPoolV3{

    // 初识大小
    static int INIT_SIZE = 10;

    // 最小值
    static int MIN_SIZE = 2;

    // 扩容增量
    static int INCREMENT = 5;



    // 从头部存，从尾部取
    static LinkedList<Connection> pool;

    static {

        try {

            Properties properties = new Properties();
            properties.load(new FileInputStream("pool.properties"));

            String initSize = properties.getProperty("init_size");
            String minSize = properties.getProperty("min_size");
            String increment = properties.getProperty("increment");

            if (null != initSize && initSize.length() > 0) {
                INIT_SIZE = Integer.valueOf(initSize);
            }

            if (null != minSize && minSize.length() > 0) {
                MIN_SIZE = Integer.valueOf(minSize);
            }

            if (null != increment && increment.length() > 0) {
                INCREMENT = Integer.valueOf(increment);
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("获取用户配置的连接池参数异常！使用默认配置!");
        }


        // 实例化
        pool = new LinkedList<Connection>();

        // 初始化
        addCapcity(INIT_SIZE);


    }


    // 获取连接
    public static Connection getConnection(){

        // 判断是否需要扩容
        if (pool.size() < MIN_SIZE) {

            addCapcity(INCREMENT);
        }

        // 取出尾部的那个连接
        Connection connection = pool.removeLast();

        return connection;

    }



    // 返回连接
    public static void returnConnection(Connection connection){

        // 把连接放到头部
        pool.addFirst(connection);

    }


    // 扩容的方法
    private static void addCapcity(int num){

        if (num < 1) return;
        for (int i = 0; i < num; i++) {
            Connection newConnection = JDBCUtils.getNewConnection();
            pool.addFirst(newConnection);
        }
    }


}
